﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Threading;

using RexToy.Logging;

namespace RexToy.Cassandra
{
    class LeastActivePolicy : ILoadBalancePolicy
    {
        private static ILog _log = LogContext.GetLogger<ILoadBalancePolicy>();

        private long[] _usage;
        private int _len;
        public void Initialize(List<DnsEndPoint> hosts)
        {
            _len = hosts.Count;
            _usage = new long[_len];
        }

        public void Pick(Cluster.Context ctx)
        {
            if (ctx.Stop)
                return;

            long min = long.MaxValue;
            int idx = 0;

            for (int i = 0; i < _len; i++)
            {
                if (_usage[i] < min)
                {
                    min = _usage[i];
                    idx = i;
                }
            }

            _usage[idx] = min + 1;//Note: Don't lock! Not need very accuracy.
            ctx.SelectedIndex = idx;
        }

        public void Recycle(Cluster.Context ctx)
        {

        }
    }
}
